package com.wcfsy.wechat.wx.job;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.wcfsy.wechat.wx.service.ActivityService;
import com.wcfsy.wechat.wx.util.WechatUtil;

/**
 *
 * 项目名称：xn-wechat-activity
 * 
 * 类名称：WechatConfigQuartz.java
 * 
 * 类描述：微信配置定时器 每一个班小时执行一次
 * 
 * 创建人： Rod Zhong
 * 
 * 创建时间：2015年7月30日 下午3:33:02
 * 
 * Copyright (c) 深圳市小牛科技有限公司-版权所有
 */
@Component
public class WechatConfigQuartz {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	private static Map<String, Boolean> ticketMap = new HashMap<String, Boolean>();
	private static String TICKET_RUN = "run";
	@Resource
	private ActivityService activityService;
	private static boolean init=true;

	public static void toggleRun(boolean run) {
		ticketMap.put(TICKET_RUN, run);
	}

	@PostConstruct
	public void init() {
		WechatConfigQuartz.toggleRun(true);
		if(init){
			init=false;
			WechatUtil.poolThreadExecutor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(10000);
						try {
							activityService.getWechatTicket();
						} catch (Exception e) {
							logger.warn("重新跑一次", e);
							activityService.getWechatTicket();
						}
					} catch (Exception e1) {
					}
				}
			});
		}
	}

	@Scheduled(cron = "0 0 1 * * ?")
	public void execute() {
		if (ticketMap.get(TICKET_RUN).booleanValue()) {
			logger.info("....................微信配置定时器start....................");
			try {
				activityService.getWechatTicket();
			} catch (Exception e) {
				logger.warn("重新跑一次", e);
				activityService.getWechatTicket();
			}
			logger.info("....................微信配置定时器end....................");
		} else {
			logger.info("....................微信更新ticket定时器挂起状态....................");
		}
	}

}
